<template>
  <div>
    <el-dialog v-model="dialogVisible" width="80%" align-center :close-on-click-modal="false" :show-close="false"
      :before-close="handleClose" destroy-on-close draggable>
      <template #header="{ close }">
        <div class="dialog-header flex justify-between items-center">
          <div v-if="!title">获奖{{ ruleForm.id ? '编辑' : '新增' }}</div>
          <div v-else>{{ title }}</div>
          <el-icon class="el-icon--left cursor-pointer" @click="close">
            <CircleCloseFilled color="#fff" />
          </el-icon>
        </div>
      </template>
      <el-form :model="ruleForm" :rules="rules" label-width="130px" ref="ruleFormRef">
        <!-- 基本信息 -->
        <div class="bg-white mt-[10px]">
          <BaseHead>基本信息</BaseHead>
          <div class="p-[10px]">

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="奖励批准号">
                  <el-input placeholder="请输入奖励批准号" v-model="ruleForm.honorSn" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="获奖类型">
                  <el-radio-group v-model="ruleForm.honorNumber">
                    <el-radio :value="1" size="large">成果奖</el-radio>
                    <el-radio :value="2" size="large">人才奖</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="奖励名称" prop="name">
                  <el-input placeholder="请输入奖励名称" v-model="ruleForm.name" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="成果名称" prop="productName">
                  <el-input placeholder="请输入成果名称" v-model="ruleForm.productName" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="发证机关" prop="honorUnit">
                  <el-input placeholder="请输入发证机关" v-model="ruleForm.honorUnit" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="获奖级别" prop="honorLevelId">
                  <el-select v-model="ruleForm.honorLevelId" placeholder="请选择获奖级别" clearable>
                    <el-option v-for="item in hjjbList" :key="item.code" :label="item.name" :value="item.code" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="获奖等级" prop="honorGradeId">
                  <el-select v-model="ruleForm.honorGradeId" placeholder="请选择获奖等级" clearable>
                    <el-option v-for="item in hjdjList" :key="item.code" :label="item.name" :value="item.code" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="奖励类别" prop="honorTypeId">
                  <el-select v-model="ruleForm.honorTypeId" placeholder="请选择奖励类别" clearable>
                    <el-option v-for="item in hjnbList" :key="item.code" :label="item.name" :value="item.code" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="获奖日期" prop="honorDate">
                  <el-date-picker v-model="ruleForm.honorDate" type="date" format="YYYY/MM/DD"
                    value-format="YYYY-MM-DD" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="成果形式" prop="productMode">
                  <el-input placeholder="请输入成果形式" v-model="ruleForm.productMode" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="总参加单位数">
                  <el-select v-model="ruleForm.totalUnitNum" placeholder="请选择总参加单位数" clearable>
                    <el-option v-for="item in 10" :key="item" :label="item" :value="item" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所属单位" prop="unitId">
                  <el-select v-model="ruleForm.unitId"
                    :disabled="(tableData && tableData[0].disable) || Cookies.get('role-key') == 'biz_kyry'"
                    placeholder="请选择所属单位" clearable>
                    <el-option v-for="item in zcgsdwList" :key="item.codeColumn" :label="item.valueColumn"
                      :value="item.codeColumn" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

          </div>
        </div>
        <!-- 详细信息 -->
        <div class="bg-white mt-[10px]">
          <BaseHead>详细信息 </BaseHead>
          <div class="p-[10px]">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="合作类型">
                  <el-radio-group v-model="ruleForm.cooperationType" @change="changecoType">
                    <el-radio value="1" size="large">独立申请</el-radio>
                    <el-radio value="2" size="large">联合申请</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="获奖金额">
                  <el-input placeholder="请输入获奖金额" @input="validateNumber" type="number" v-model="ruleForm.honorFee"
                    clearable>
                    <template #append>
                      万元
                    </template></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="本校奖金比例" v-show="ruleForm.cooperationType == 2">
                  <el-input placeholder="" v-model.number="ruleForm.schoolScale" @input="handleInput" type="number"
                    clearable>
                    <template #append>
                      %
                    </template></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="完成单位" prop="completeUnit">
                  <el-input placeholder="请输入完成单位" v-model="ruleForm.completeUnit" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="单位排名">
                  <div class="flex w-full">
                    <div class="tipBox">第</div> <el-select style="flex: 1;" v-model="ruleForm.unitOrderId"
                      placeholder="请选择单位排名" clearable>
                      <el-option v-for="item in 10" :key="item" :label="item" :value="item" />
                    </el-select>
                    <div class="tipBox" style="width: 68px;">单位</div>
                  </div>

                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="学科门类" prop="subjectClassId">
                  <el-radio-group v-model="ruleForm.subjectClassId" @change="changeSub">
                    <el-radio value="2" size="large">科技类</el-radio>
                    <el-radio value="1" size="large">社科类</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="学科分类" prop="subjectId">
                  <el-select v-model="ruleForm.subjectId" v-if="ruleForm.subjectClassId == '2'" placeholder="请选择学科分类" clearable>
                    <el-option v-for="item in kjxkflList" :key="item.id" :label="item.label" :value="item.id" />
                  </el-select>
                  <el-select v-model="ruleForm.subjectId" v-else placeholder="请选择学科分类" clearable>
                    <el-option v-for="item in skxkflList" :key="item.id" :label="item.label" :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="项目来源" prop="projectSourceId">
                  <el-select v-model="ruleForm.projectSourceId" placeholder="请选择项目来源">
                    <el-option v-for="item in projectSourceList.value" :key="item.id" :label="item.label" :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="奖励证书" prop="fileIds">
                  <FileUpload :uploadUrl="uploadUrl" v-model="fileList" @change="fileChange">
                  </FileUpload>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="备注">
                  <el-input v-model="ruleForm.note" type="textarea" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>
        <!-- 完成人信息 -->
        <div class="bg-white mt-[10px]">
          <BaseHead>完成人信息
            <template v-slot:Rslot>
              <el-button @click="addHonor">添加</el-button>
            </template>
          </BaseHead>
          <div class="p-[10px]">
            <el-table :data="tableData" border style="width: 100%">
              <el-table-column align="center" type="index" label="署名顺序" width="80" />
              <el-table-column align="center" prop="date" label="完成人类型">
                <template #default="scope">
                  <el-select v-model="scope.row.authorType"
                    :disabled="scope.row.disable || (Cookies.get('role-key') == 'biz_kyry' && scope.$index == 0)"
                    @change="e => {
      selectAuthorType(e, scope.$index);
    }">
                    <el-option v-for="item in wcrTypelist" :key="item.code" :label="item.name" :value="item.code" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column align="center" prop="name" label="完成人姓名">
                <template #default="scope">
                  <el-select v-model="scope.row.authorName"
                    :disabled="scope.row.disable || (Cookies.get('role-key') == 'biz_kyry' && scope.$index == 0)"
                    @change="e => {
      selectAuthor(e, scope.$index, scope.row);
    }" v-if="scope.row.authorType != '3'" filterable remote reserve-keyword placeholder="请输入关键字检索"
                    :remote-method="remoteMethod" :loading="loading">
                    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                  <!-- <el-autocomplete v-model="scope.row.authorName" v-else placeholder="请输入关键字检索" value-key="label"
                    :fetch-suggestions="querySearchAsync" @select="e => { handleSelect(e, scope.$index) }" /> -->
                  <el-input v-model="scope.row.authorName" v-else />
                </template>
              </el-table-column>
              <el-table-column align="center" prop="address" label="学历">
                <template #default="scope">
                  <el-select v-model="scope.row.eduLevelId">
                    <el-option v-for="item in xlList" :key="item.code" :label="item.name" :value="item.code" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column align="center" prop="address" label="工作单位">
                <template #default="scope">
                  <el-input v-model="scope.row.authorUnit" v-if="scope.row.authorType == '3'" />
                  <el-select v-model="scope.row.authorUnitId" :disabled="scope.row.authorType == '1'" @change="e => {
      changUnit(e, scope.$index);
    }" v-else placeholder=" 请选择所属单位" clearable>
                    <el-option v-for=" item in sydwList" :key="item.codeColumn" :label="item.valueColumn"
                      :value="item.codeColumn" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column align="center" prop="address" label="职称">
                <template #default="scope">
                  <el-tree-select v-model="scope.row.titleId" node-key="id" :data="zcList" :render-after-expand="false"
                    :props="defaultProps" />
                </template>
              </el-table-column>
              <el-table-column align="center" prop="address" label="贡献率（%）">
                <template #default="scope">
                  <el-input placeholder="" v-model.number="scope.row.workRatio" @input="e => {
      handleInput1(e, scope.$index);
    }
      " type="number">
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column align="center" prop="address" label="操作">
                <template #default="scope">

                  <el-link type="primary" :underline="false"
                    v-if="!scope.row.disable && !(Cookies.get('role-key') == 'biz_kyry' && scope.$index == 0)"
                    @click="delHonor(scope.$index)">删除</el-link>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <div class="operate-btns">
            <el-button type="primary" @click="submitForm(ruleFormRef, '-1')" v-if="ruleForm.checkstatus != '2'"
              :loading="btnLoading">暂存</el-button>
            <el-button type="primary" @click="submitForm(ruleFormRef)" v-if="checkEditButtonT()"
              :loading="btnLoading">{{
      Cookies.get("role-key") ==
        'biz_kyry' ? '提交' : ruleForm.checkstatus == '2' ? '保存' :
        '保存并通过' }}</el-button>
            <el-button type="primary" @click="closeDiglog">关闭</el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import BaseHead from "@/views/project/components/BaseHead.vue";
import BaseTable from "@/views/project/components/BaseTable.vue";
import { getPersonDetails } from "@/api/achievement/common.js"
import { getHonoradd, getHonorupdate } from "@/api/achievement/cghj"
import { ElMessage, ElMessageBox } from "element-plus";
import FileUpload from "@/views/achievement/components/FileUpload.vue"
import Cookies from 'js-cookie'
import useUserStore from "@/store/modules/user";
import useCommonFetch from "@/hooks/useCommonFetch";
let projectSourceList = ref([]); //项目来源下拉数据

const dialogVisible = defineModel();
const props = defineProps({
  hjjbList: Array,
  hjdjList: Array,
  hjnbList: Array,
  xmlyList: Array,
  xlList: Array,
  zcList: Array,
  zcgsdwList: Array,
  kjxkflList: Array,
  skxkflList: Array,
  title: String,
  sydwList: Array,

})
const defaultProps = {
  children: 'children',
  label: 'label',
}
const tableData = reactive([
  {
    authorType: '1',
    eduLevelId: '',
    authorName: '',
    titleId: '',
    authorUnit: '',
    authorUnitId: '',
    workRatio: null,
    personId: '',   //userId
    orderId: 1,
    authorAccount: "",   //职工号
    sexId: '',
    subjectId: ""
  },
]);
const addHonor = () => {
  tableData.push({
    authorType: '1',
    eduLevelId: '',
    authorName: '',
    titleId: '',
    authorUnit: '',
    authorUnitId: '',
    workRatio: null,
    personId: '',   //userId
    orderId: tableData.length ? tableData[tableData.length - 1].orderId + 1 : 1,
    authorAccount: "",   //职工号
    sexId: '',
    subjectId: ""
  })
}
const delHonor = (index) => {
  tableData.splice(index, 1)
}
const selectAuthorType = (e, index) => {
  let type1 = tableData[index].authorType
  let orderId1 = tableData[index].orderId
  tableData[index] = {
    authorType: type1,
    eduLevelId: '',
    authorName: '',
    titleId: '',
    authorUnit: '',
    authorUnitId: '',
    workRatio: null,
    personId: '',   //userId
    orderId: orderId1,
    authorAccount: "",   //职工号
    sexId: '',
    subjectId: ""
  }
  if (e == '3') {
    tableData[index].personId = '3'
  }
}
const wcrTypelist = reactive([
  {
    code: '1',
    name: '教师'
  },
  {
    code: '2',
    name: '学生'
  },
  {
    code: '3',
    name: '校外'
  },
]);
const ruleForm = reactive({
  honorSn: '',
  honorNumber: 1,
  name: '',
  productName: '',
  honorUnit: '',
  honorLevelId: "",
  honorGradeId: '',
  honorTypeId: '',
  honorDate: '',
  productMode: '',
  totalUnitNum: '',
  unitId: '',
  cooperationType: '1',
  honorFee: '',
  schoolScale: null,
  completeUnit: '',
  unitOrderId: '',
  subjectClassId: '',
  subjectId: '',
  projectSourceId: '',
  note: '',
  fileIds: '',
})
const rules = reactive({
  name: [
    { required: true, message: '请输入奖励名称', trigger: 'blur' },
  ],
  productName: [
    { required: true, message: '请输入成果名称', trigger: 'blur' },
  ],
  honorUnit: [
    { required: true, message: '请输入发证机关', trigger: 'blur' },
  ],
  productMode: [
    { required: true, message: '请输入成果形式', trigger: 'blur' },
  ],
  completeUnit: [
    { required: true, message: '请输入完成单位', trigger: 'blur' },
  ],
  honorLevelId: [
    {
      required: true,
      message: '请选择获奖级别',
      trigger: 'change',
    },
  ],
  honorGradeId: [
    {
      required: true,
      message: '请选择获奖等级',
      trigger: 'change',
    },
  ],
  honorTypeId: [
    {
      required: true,
      message: '请选择奖励类别',
      trigger: 'change',
    },
  ],
  honorDate: [
    {
      required: true,
      message: '请选择获奖日期',
      trigger: 'change',
    },
  ],
  unitId: [
    {
      required: true,
      message: '请选择所属单位',
      trigger: 'change',
    },
  ],
  subjectClassId: [
    {
      required: true,
      message: '请选择学科门类',
      trigger: 'change',
    },
  ],
  subjectId: [
    {
      required: true,
      message: '请选择学科分类',
      trigger: 'change',
    },
  ],
  fileIds: [
    {
      required: true,
      message: '请上传证书',
    },
  ],
  // projectSourceId: [
  //   {
  //     required: true,
  //     message: '请选择项目来源',
  //     trigger: 'change',
  //   },
  // ],
})
const handleInput = (value) => {
  if (value !== null) { // 检查是否为null（非数字）或已经是数字且在范围内
    ruleForm.schoolScale = Math.max(0, Math.min(100, value)); // 确保值在0到100之间
  } else {
    ruleForm.schoolScale = null; // 重置为null，或者你可以设置为一个默认值，比如0或空字符串，取决于你的需求
  }
};
const handleInput1 = (value, index) => {
  if (value !== null) { // 检查是否为null（非数字）或已经是数字且在范围内
    tableData[index].workRatio = Math.max(0, Math.min(100, value)); // 确保值在0到100之间
  } else {
    tableData[index].workRatio = null; // 重置为null，或者你可以设置为一个默认值，比如0或空字符串，取决于你的需求
  }
};
const subType = ref(2)
const changeSub = () => {
  if (ruleForm.subjectClassId == 1) {
    ruleForm.subjectId = '';
    ruleForm.projectSourceId = '';
    subType.value = 1;
  } else {
    ruleForm.subjectId = '';
    ruleForm.projectSourceId = '';
    subType.value = 2;
  }
}
const querySearchAsync = (queryString, cb) => {
  console.log(queryString, 'queryString')
  if (queryString) {
    let pamrs = {
      name: queryString
    }
    getPersonDetails(pamrs).then(res => {
      console.log(res, 'res')
      if (res.code == 200) {
        let arr = res.data;
        arr.map(item => {
          item.value = item.name;
          item.label = item.name;
        })
        cb(arr);
      }
    })
  } else {
    cb([]);
  }

  // const results = queryString
  //   ? links.value.filter(createFilter(queryString))
  //   : links.value

  // clearTimeout(timeout)
  // timeout = setTimeout(() => {
  //   cb(results)
  // }, 3000 * Math.random())
}


const changecoType = () => {
  if (ruleForm.cooperationType == 1) {
    ruleForm.schoolScale = null
  }
}
const handleSelect = (item) => {
  tableData[index].personId = item.id
  tableData[index].authorAccount = item.account
  tableData[index].sexId = item.sexId
  tableData[index].subjectId = item.subjectId
  tableData[index].authorUnitId = item.unitId
  tableData[index].authorUnit = item.unitName
  tableData[index].eduLevelId = item.eduLevelId
  tableData[index].titleId = item.titleId
}
const changUnit = (value, index) => {
  console.log(value, 'unitvalue')
  if (item) {
    tableData[index].authorUnit = zcgsdwList.value.find(item => item.codeColumn == value).valueColumn
  }
}
const options = ref([])
const loading = ref(false)
const remoteMethod = (query) => {
  if (query) {
    loading.value = true
    let pamrs = {
      name: query
    }
    getPersonDetails(pamrs).then(res => {
      console.log(res, 'res')
      if (res.code == 200) {
        let arr = res.data;
        arr.map(item => {
          item.value = item.name + ' ' + item.account + ' ' + item.unitName;
          item.label = item.name + ' ' + item.account + ' ' + item.unitName;
        })
        options.value = arr
        loading.value = false
      }
    })
  } else {
    options.value = []
  }
}
// unit_id
const selectAuthor = (e, index, row) => {
  console.log(e, index, row)
  console.log(options.value.find(item => item.value == e))
  let userInfo = options.value.find(item => item.value == e)
  let cfuserInfo = tableData.find(item => item.personId == userInfo.id)
  if (cfuserInfo) {
    tableData[index].authorName = ''
    ElMessage({
      message: '此人已在列表中，请勿重复添加',
      type: 'error',
    })
    return;
  } else {
    tableData[index].authorName = userInfo.name
    tableData[index].personId = userInfo.id
    tableData[index].authorAccount = userInfo.account
    tableData[index].sexId = userInfo.sexId
    tableData[index].subjectId = userInfo.subjectId
    tableData[index].authorUnitId = userInfo.unitId
    tableData[index].authorUnit = userInfo.unitName
    tableData[index].eduLevelId = userInfo.eduLevelId
    tableData[index].titleId = userInfo.titleId
  }
}

const btnLoading = ref(false)

const ruleFormRef = ref()
const submitForm = async (formEl, i) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      let params = {
        ...ruleForm,
      }

      if (tableData.length == 0) {
        ElMessage({
          message: '请添加至少一条完成人信息',
          type: 'error',
        })
        return;
      } else if (tableData[0].authorName == '') {
        ElMessage({
          message: '请添加至少一条完成人信息',
          type: 'error',
        })
        return;
      } else {
        let ContributionRate = 0
        tableData.forEach(item => {
          ContributionRate += item.workRatio
        })
        if (ContributionRate > 100) {
          ElMessage({
            message: '贡献率不能大于100',
            type: 'error',
          })
          return;
        }
      }
      params.honorAuthorDTOs = tableData
      params.submitType = i ? i : Cookies.get("role-key") == 'biz_kyry' ? '1' : '2'
      if (i == '-1') {
        if (!ruleForm.id || Cookies.get("role-key") == 'biz_kyry') {
        } else {
          params.submitType = params.checkstatus
        }
      }
      console.log(params, 'params')
      btnLoading.value = true;
      if (params.id) {
        getHonorupdate(params).then((res) => {
          if (res.code == 200) {
            ElMessage({
              message: res.msg,
              type: 'success',
            })
            dialogVisible.value = false
            initData()
            emit('callBack', "")
          } else {
            ElMessage({
              message: res.msg,
              type: 'error',
            })
          }
          btnLoading.value = false;
        })
      } else {
        getHonoradd(params).then((res) => {
          if (res.code == 200) {
            ElMessage({
              message: res.msg,
              type: 'success',
            })
            dialogVisible.value = false
            initData()
            emit('callBack', "")
          } else {
            ElMessage({
              message: res.msg,
              type: 'error',
            })
          }
          btnLoading.value = false;
        })
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

const uploadUrl = `/commonFile/uploadFile?modelName=honorApply`;
const fileList = ref([]);
const emit = defineEmits(['callBack']);
const handleClose = (done) => {
  tableData.length = 0;
  tableData.push(
    {
      authorType: '1',
      eduLevelId: '',
      authorName: '',
      titleId: '',
      authorUnit: '',
      authorUnitId: '',
      workRatio: null,
      personId: '',   //userId
      orderId: 1,
      authorAccount: "",   //职工号
      sexId: '',
      subjectId: ""
    })
  Object.assign(ruleForm, {
    honorSn: '',
    honorNumber: 1,
    name: '',
    productName: '',
    honorUnit: '',
    honorLevelId: "",
    honorGradeId: '',
    honorTypeId: '',
    honorDate: '',
    productMode: '',
    totalUnitNum: '',
    unitId: '',
    cooperationType: '1',
    honorFee: '',
    schoolScale: null,
    completeUnit: '',
    unitOrderId: '',
    subjectClassId: '',
    subjectId: '',
    projectSourceId: '',
    note: '',
    fileIds: '',
  })
  delete ruleForm.id;
  delete ruleForm.checkstatus;
  fileList.value = [];
  emit('callBack', "2")
  done()
}
const closeDiglog = () => {
  dialogVisible.value = false
  tableData.length = 0;
  tableData.push(
    {
      authorType: '1',
      eduLevelId: '',
      authorName: '',
      titleId: '',
      authorUnit: '',
      authorUnitId: '',
      workRatio: null,
      personId: '',   //userId
      orderId: 1,
      authorAccount: "",   //职工号
      sexId: '',
      subjectId: ""
    })
  Object.assign(ruleForm, {
    honorSn: '',
    honorNumber: 1,
    name: '',
    productName: '',
    honorUnit: '',
    honorLevelId: "",
    honorGradeId: '',
    honorTypeId: '',
    honorDate: '',
    productMode: '',
    totalUnitNum: '',
    unitId: '',
    cooperationType: '1',
    honorFee: '',
    schoolScale: null,
    completeUnit: '',
    unitOrderId: '',
    subjectClassId: '',
    subjectId: '',
    projectSourceId: '',
    note: '',
    fileIds: '',
  })
  delete ruleForm.id;
  delete ruleForm.checkstatus;
  fileList.value = [];
}

const initData = () => {
  tableData.length = 0;
  tableData.push(
    {
      authorType: '1',
      eduLevelId: '',
      authorName: '',
      titleId: '',
      authorUnit: '',
      authorUnitId: '',
      workRatio: null,
      personId: '',   //userId
      orderId: 1,
      authorAccount: "",   //职工号
      sexId: '',
      subjectId: ""
    })
  Object.assign(ruleForm, {
    honorSn: '',
    honorNumber: 1,
    name: '',
    productName: '',
    honorUnit: '',
    honorLevelId: "",
    honorGradeId: '',
    honorTypeId: '',
    honorDate: '',
    productMode: '',
    totalUnitNum: '',
    unitId: '',
    cooperationType: '1',
    honorFee: '',
    schoolScale: null,
    completeUnit: '',
    unitOrderId: '',
    subjectClassId: '',
    subjectId: '',
    projectSourceId: '',
    note: '',
    fileIds: '',
  })
  delete ruleForm.id;
  delete ruleForm.checkstatus;
  fileList.value = [];
}



const getRuleForm = (i) => {
  console.log(i, 'info')
  if (i.honorAuthorVOs && i.honorAuthorVOs.length > 0) {
    console.log(tableData, 'tableData')
    tableData.length = 0; // 清空数组
    tableData.push(...i.honorAuthorVOs); // 添加新元素

  }
  if (i.fileList && i.fileList.length > 0) {
    fileList.value = i.fileList.map((item) => {
      return {
        name: item.fileName,
        id: item.id,
      };
    });
  }
  for (const key in i) {
    ruleForm[key] = i[key];
  }
  console.log(ruleForm, 'ruleForm')
}

//上传的文件改变
const fileChange = () => {
  const ids = fileList.value.map((item) => {
    const id = item.response ? item.response.data : item.id;
    return id;
  });
  ruleForm.fileIds = ids.join(",");
};

const checkEditButtonT = () => {
  console.log(Cookies.get("role-key"))
  console.log(ruleForm.isAuditor)

  if (Cookies.get("role-key") == 'biz_kyry') {
    return true
  } else if (Cookies.get("role-key") == 'biz_kyms') {
    if (ruleForm.checkstatus == '1' && ruleForm.isAuditor) {
      return true
    } else {
      return false
    }
  } else if (Cookies.get("role-key") == 'biz_kycgly') {
    if (ruleForm.checkstatus == '1') {
      return ruleForm.isAuditor ? true : false
    } else {
      return true
    }
  } else {
    return false
  }
}

const userStore = useUserStore();

const getKyryInfo = () => {
  if (Cookies.get("role-key") == 'biz_kyry') {
    let kyryInfo = {
      authorType: '1',
      eduLevelId: '',
      authorName: '',
      isTxAuthor: '0',
      titleId: '',
      authorUnit: '',
      authorUnitId: '',
      workRatio: null,
      personId: '',   //userId
      orderId: 1,
      authorAccount: "",   //职工号
      sexId: '',
      subjectId: "",
      unitId: '',
      unitName: '',
      disable: true
    }
    let pamrs = {
      account: userStore.account
    }
    let kyryInfoArr = []
    getPersonDetails(pamrs).then(res => {
      if (res.code == 200) {
        kyryInfoArr = res.data.filter((item) => {
          return item.name == userStore.nickName
        });
        if (kyryInfoArr && kyryInfoArr.length) {
          kyryInfo.authorName = kyryInfoArr[0].name
          kyryInfo.personId = kyryInfoArr[0].id
          kyryInfo.authorAccount = kyryInfoArr[0].account
          kyryInfo.sexId = kyryInfoArr[0].sexId
          kyryInfo.subjectId = kyryInfoArr[0].subjectId
          kyryInfo.authorUnitId = kyryInfoArr[0].unitId
          kyryInfo.authorUnit = kyryInfoArr[0].unitName
          kyryInfo.eduLevelId = kyryInfoArr[0].eduLevelId
          kyryInfo.titleId = kyryInfoArr[0].titleId
          let zcTableData = [kyryInfo]
          tableData.length = 0;
          tableData.push(...zcTableData);
          if (zcTableData[0].authorUnitId) {
            ruleForm.unitId = zcTableData[0].authorUnitId
          }
        }
      }
    })
  }
}

const validateNumber = (value) => {
  const minValue = 0; // 定义最小值
  if (value < minValue) {
    ruleForm.honorFee = minValue; // 或者设置为空字符串或上一个有效值
  }
  // 使用正则表达式限制小数点后最多4位
  ruleForm.honorFee = value.toString().replace(/[^0-9.]/g, '').replace(/(\.\d{6})\d*/g, '$1');
};

//监听统计归属的值改变
watch(
  () => ruleForm.subjectClassId,
  (newVal) => {
    projectSourceList.value = useCommonFetch("项目来源", newVal);
  }
);


defineExpose({
  getRuleForm,
  getKyryInfo
})
</script>

<style scoped lang="scss">
@import url("@/views/achievement/index.scss");
</style>
